import os
from collections import defaultdict
from glob import glob

from ExcelUtils import get_data_by_row

def task(file):
    result = defaultdict(list)
    _num, _name, _clazz = '', '', ''
    header = get_data_by_row(file, 0, 1, 0, 0)
    for title in header:
        for i in range(len(title)):
            item = title[i]
            if item == '姓名':
                _name = i
            elif item == '学号':
                _num = i
            elif item == '班级':
                _clazz = i
    data = get_data_by_row(file, 1, 0, 0, 0)
    for entry in data:
        num = entry[_num]
        name = entry[_name]
        clazz = entry[_clazz]
        if clazz in result:
            result[clazz].append(f'{num} {name}')
        else:
            result[clazz] = [f'{num} {name}']
        print(f'{clazz} {num} {name}')
    for _clazz, _contents in result.items():
        file_name = os.path.join('template', 'student_list', _clazz + '.txt')
        with open(file_name, 'w', encoding='utf-8') as f:
            for i, _content in enumerate(_contents):
                if i == len(_contents) - 1:
                    f.write(_content)
                else:
                    f.write(_content + '\n')


if __name__ == '__main__':
    _dir = "d:\\恒星\\学生名单"
    files = glob(os.path.join(_dir, "*.xlsx"))
    for file in files:
        task(file)
